import sys

try:
    if sys.platform == "win32":
        import _wincon
        Console = _wincon.Console
        install_readline = _wincon.install_readline
    else:
        from _cursescon import Console
except ImportError:
    raise ImportError, "installation error: cannot find a console driver"

#
# console factory (if you don't want to redirect stdout/stderr,
# simply instantiate the Console class yourself)

def getconsole(buffer=1):
    """Get a console handle.

    If buffer is non-zero, a new console buffer is allocated and
    installed.  Otherwise, this returns a handle to the current
    console buffer"""

    c = Console(buffer)

    # try to redirect stdout and stderr
    try:
        if sys.stdout.isatty():
            sys.stdout = c
    except:
        pass
    try:
        if sys.stderr.isatty():
            sys.stderr = c
    except:
        pass

    return c
